package com.itcast.homework05.work04;

import java.util.Arrays;

/*
有数组：[23 , 78, 12 , 45 , 11 , 99]。现需要查找11这个元素在数组中出现的索引，
请问是否可以使用二分查找进行实现
*/
public class Test {
    public static void main(String[] args) {
        int[] arr = {23, 78, 12, 45, 11, 99};
        Arrays.sort(arr);
        int taget=arr[0];
        int i = binarySearch(arr, taget);
        System.out.println("11这个元素在数组中出现的索引为："+i);

    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid]<target){
                left=mid+1;
            }else if (arr[mid]>target){
                right=mid-1;
            }else {
                return mid;
            }
        }
        return -1;
    }
}
